<?php

namespace App\Models\Panx;

use App\Models\Concerns\ScopeFilterable;
use App\Models\Customer\Customer;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class MaterialSale
 *
 * @method self filterCustomerId($customer_id)
 * @method self filterName($name)
 * @method self filterOperator($operator)
 *
 * @mixin Builder
 */
class MaterialSale extends Model
{
    use ScopeFilterable;

    protected $table = 'material_sales';
    protected $guarded = [];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function customer()
    {
        return $this->belongsTo(Customer::class, 'customer_id', 'id')
            ->select(['id', 'name']);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function materialPurchase()
    {
        return $this->belongsTo(MaterialPurchase::class, 'material_purchase_id', 'id');

    }

    /**
     * @used-by filterCustomerId
     * @param Builder $query
     * @param $customer_id
     * @return Builder
     */
    public function scopeFilterCustomerId(Builder $query, $customer_id)
    {
        if (! $customer_id) return $query;

        return $query->where('customer_id', $customer_id);
    }

    /**
     * @used-by filterName
     * @param Builder $query
     * @param $name
     * @return Builder
     */
    public function scopeFilterName(Builder $query, $name)
    {
        if (! $name) return $query;

        return $query->whereHas('materialPurchase', function (Builder $query) use($name){
            return $query->whereHas('material', function(Builder $query) use($name){
                return $query->where('name', 'like', '%'.$name.'%');
            });
        });
    }

    /**
     * @used-by filterOperator
     * @param Builder $query
     * @param $operator
     * @return Builder
     */
    public function scopeFilterOperator(Builder $query, $operator)
    {
        if (! $operator) return $query;

        return $query->where('operator', 'like', '%'.$operator.'%');
    }
}
